import java.util.Arrays;

/**
 * @author : retainv
 * @date : 2024/3/15 16:26
 */
public class Leetcode1679K和数对的最大数目 {
    public static void main(String[] args) {
//        int[] nums = {4,4,1,3,1,3,2,2,5,5,1,5,2,1,2,3,5,4};
        int[] nums = {2,2,2,3,1,1,4,1};
//        int[] nums = {3,1,3,4,3};
        System.out.println(maxOperations(nums, 4));
    }
    public static int maxOperations(int[] nums, int k) {
        Arrays.sort(nums);
        int n = nums.length;
        int i = 0;
        int j = n - 1;
        int num = 0;
        while (i < j) {
            while (i < j && nums[i] >= k) {
                i++;
            }
            while (i < j && nums[j] >= k) {
                j--;
            }
            if (i >= j) return num;
            if(nums[i] + nums[j] > k) {
                j--;
            }else if (nums[i] + nums[j] < k) {
                i++;
            }else {
                num++;
                i++;
                j--;
            }
        }
        return num;
    }
}
